package com.eco.fanliapp.job.userjob;

import com.eco.fanliapp.service.WeixinUtil;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * 用户关注公众号openId处理
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class HandleAccessTokenTask implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(HandleAccessTokenTask.class);

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public HandleAccessTokenTask() {
    }

    @Override
    public void execute(JobExecutionContext context)  {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap =  jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行用户关注公众号openId处理任务-HandleAccessTokenTask：executeCount="+executeCount+"--startTime="+startTime);

        try {
            //从redis中获取
            String access_token =(String)redisTemplate.opsForValue().get("access_token");
            if(access_token != null || !"".equals(access_token)){
                redisTemplate.delete("access_token");
            }
            try {
                access_token = WeixinUtil.getAccessToken();
            }catch (Exception e){
            }
            redisTemplate.opsForValue().set("access_token",access_token, 3600, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("刷新access_token错误");
        }

        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行w用户关注公众号openId处理任务-HandleAccessTokenTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));
    }
}
